<template>
	<section>
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.title" placeholder="商品名称"></el-input>
				</el-form-item>

				<el-form-item >
					<el-select v-model="filters.categoryId"   filterable placeholder="请选择所属商品">
						<el-option
								v-for="item in categoryOptions"
								:key="item.title"
								:label="item.title"
								:value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search(1)">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search(0)">取消</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<el-table highlight-current-row v-loading="listLoading" @selection-change="selsChange"
				  :data="goodsData"
				  style="width: 100%">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="title" label="商品名称" width="180" >
			</el-table-column>
			<el-table-column prop="titleUg" label="商品名称(Ug)" width="180" >
			</el-table-column>
			<el-table-column prop="thumb" label="商品图片" width="80" >
				<template  slot-scope="scope" >
					<img :src="renderImage(scope.row.thumb)" height="60" style="margin-top: 3px" />
				</template>
			</el-table-column>
			<el-table-column prop="category" label="所属分类" width="180">
			</el-table-column>
			<el-table-column prop="price" label="商品价格" width="120" ></el-table-column>
			<el-table-column prop="bazarPrice" label="市场价" ></el-table-column>
			<el-table-column prop="stock" label="库存" ></el-table-column>
			<el-table-column prop="sale" label="销量" ></el-table-column>
			<el-table-column prop="comment" label="评论" ></el-table-column>
			<el-table-column prop="view" label="查看" ></el-table-column>
			<el-table-column prop="createTimeStr" label="创建时间" width="180" sortable="true" >
			</el-table-column>
			<el-table-column prop="status" label="状态" width="120"  :formatter="stateFormat" ></el-table-column>
			<el-table-column prop="actions" label="操作" width="290" fixed="right">
				<template slot-scope="scope" >
					<el-button type="primary" size="small" @click="specification(scope.$index,scope.row)" >商品规格</el-button>
					<el-button type="warning" v-if="scope.row.status==1" size="small" @click="handleState(scope.$index, scope.row)">下架</el-button>
					<el-button type="success" v-if="scope.row.status==0" size="small" @click="handleState(scope.$index, scope.row)">上架</el-button>
					<el-button type="primary" size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<el-col :span="24" class="toolbar">
			<template >
				<div class="block">
					<el-pagination
							@size-change="handleSizeChange"
							@current-change="handleCurrentChange"
							:current-page="pager.page"
							:page-sizes="pager.limits"
							:page-size="pager.limit"
							layout="total, sizes, prev, pager, next, jumper"
							:total="pager.total">
					</el-pagination>
				</div>
			</template>
		</el-col>

		<el-col >
			<el-button type="success" @click="batchRemove" :disabled="this.sels.length===0">批量上架</el-button>
			<el-button type="warning" @click="batchRemove" :disabled="this.sels.length===0">批量下架</el-button>
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
		</el-col>

		<!--新增界面-->
		<el-dialog :title="formTitle" v-model="formVisible" :close-on-click-modal="false">
			<el-form :model="goodsModel" label-width="120px"  ref="goodsModel" :rules="formRules" >
				<el-row>
					<el-col :span="12">
						<el-form-item label="商品名称" prop="title">
							<el-input v-model="goodsModel.title" auto-complete="off"></el-input>
						</el-form-item>
						<el-form-item label="商品名称(Ug)" prop="title">
							<el-input v-model="goodsModel.titleUg" auto-complete="off"></el-input>
						</el-form-item>
						<el-form-item label="所属分类" prop="parentId" >
							<template>
								<el-select v-model="goodsModel.categoryId" filterable placeholder="请选择所属商品">
									<el-option
											v-for="item in categoryOptions"
											:key="item.id"
											:label="item.title"
											:value="item.id">
									</el-option>
								</el-select>
							</template>
						</el-form-item>

						<el-form-item  label="商品价格" prop="price" >
							<el-input v-model="goodsModel.price" auto-complete="off" ></el-input>
						</el-form-item>
						<el-form-item  label="市场价格" prop="bazarPrice" >
							<el-input v-model="goodsModel.bazarPrice" auto-complete="off" ></el-input>
						</el-form-item>

						<el-form-item  label="库存" prop="stock" >
							<el-input v-model="goodsModel.stock" auto-complete="off" ></el-input>
						</el-form-item>
						<el-form-item  label="销量" prop="sale" >
							<el-input v-model="goodsModel.sale" auto-complete="off" ></el-input>
						</el-form-item>
						<el-form-item  label="查看" prop="view" >
							<el-input v-model="goodsModel.view" auto-complete="off" ></el-input>
						</el-form-item>
						<el-form-item  label="评论" prop="comment" >
							<el-input v-model="goodsModel.comment" auto-complete="off" ></el-input>
						</el-form-item>

						<el-form-item label="状态" prop="status" >
							<el-radio-group v-model="goodsModel.status">
								<el-radio class="radio" :label="1" >上架</el-radio>
								<el-radio class="radio" :label="2">下架</el-radio>
							</el-radio-group>
						</el-form-item>

						<el-form-item prop="description" label="商品描述" >
							<el-input v-model="goodsModel.description" type="textarea" placeholder="请输入商品描述" ></el-input>
						</el-form-item>

					</el-col>
					<el-col :span="12">
						<el-form-item label="商品主图" prop="src" >
							<el-upload
									action="/admin/goods/upload"
									:on-success="onUploadSuccess"
									list-type="picture-card"
									:limit="thumbUploadSize"
									:show-file-list="false"
							>
								<img v-if="goodsModel.thumb && goodsModel.id > 0" :src="renderImage(goodsModel.thumb)" class="avatar">
								<i v-if="!goodsModel.thumb || goodsModel.id == 0 " class="el-icon-upload" ></i>
							</el-upload>
						</el-form-item>
						<el-form-item label="商品图册" prop="images" >
							<el-upload
									action="/admin/goods/upload"
									:on-success="onUploadListSuccess"
									list-type="picture"
									:file-list="pictures"
									:on-remove="removeListImage"
							>
								<i class="el-icon-upload" ></i>
							</el-upload>
						</el-form-item>
					</el-col>
				</el-row>

				<el-form-item label="详情">
					<div class="edit_container">
						<el-upload
								class="avatar-uploader"
								 action="/admin/goods/upload"
								 name="img"
								:headers="header"
								:show-file-list="false"
								:on-success="qeUploadSuccess"
								:on-error="qeUploadError"
								:before-upload="qeBeforeUpload" >
						</el-upload>
						<quill-editor
								class="QEEditor"
								v-model="goodsModel.information"
								ref="myQuillEditor"
								:options="editorOption"
								@change="onEditorChange($event)"
						>
						</quill-editor>
					</div>
				</el-form-item>

			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="formVisible = false">取消</el-button>
				<el-button type="primary" @click.native="submit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

        <el-dialog title="商品规格" v-model="specVisible" :close-on-click-modal="false" >
            <div class="-header" >
                <el-button size="middle" type="primary" >新增规格</el-button>
            </div>
        </el-dialog>

	</section>
</template>
<style>
	.avatar{
		width: 100%;
		max-height: 148px;
	}
</style>
<script>
	import {getAllCategory, getGoodsData, goodsStatus, saveGoodsData} from "../../api/api";
	const toolbarOptions = [
		['bold', 'italic', 'underline', 'strike'],        // toggled buttons
		[{'header': 1}, {'header': 2}],               // custom button values
		[{'list': 'ordered'}, {'list': 'bullet'}],
		[{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
		[{'direction': 'rtl'}],                         // text direction
		[{'size': ['small', false, 'large', 'huge']}],  // custom dropdown
		[{'header': [1, 2, 3, 4, 5, 6, false]}],
		[{'color': []}, {'background': []}],          // dropdown with defaults from theme
		[{'font': []}],
		[{'align': []}],
		['link', 'image'],
		['clean']

	]

	export default {
		name: "List",
		data() {
			return {
				filters:{
					title:''
				}
				,categoryOptions:[]
				,goodsData:[]
				,listLoading:false
				,editLoading:false
				,goods:{}
				,list:[]
				,pager:{
					total:0,
					page:1,
					size:1,
					limit:12,
					limits:[8,12,15,24]
				},
				sels:[],
				goodsModel:{},
				pictures:[],
				thumbUploadSize:1,
				thumbMultiUpload:false,
				formTitle:"",
				formVisible:false,
				header: {
					// token: sessionStorage.token
					// 有的图片服务器要求请求头需要有token
				},
				myQuillEditor:{},
				quillUpdateImg:false,
				editorOption: {
				placeholder: '',
						theme: 'snow',  // or 'bubble'
						modules: {
						toolbar: {
							container: toolbarOptions,
									handlers: {
								'image': function (value) {
									if (value) {
										// 触发input框选择图片文件
										document.querySelector('.avatar-uploader input').click()
									} else {
										this.quill.format('image', false);
									}
								}
							}
						}
					}
				},
				formRules: {
					title: [
						{required: true, message: '请输入商品名称', trigger: 'blur'}
					]
				},
                specVisible:false
            }
		},
		methods:{
            specification(index,row){
                // this.specVisible = true
				this.$router.push({
					path:'/goods/spec',
					query:{
						id:row.id
					}
				})
            },
			selsChange(val){
				this.sels = val;
			},
			renderImage(url){
				if(url.substr(0,6)=='http:/' || url.substr(0,7)=='https:/'){
					return url;
				}else{
					return this.imageService + url;
				}
			},
			stateFormat(row){

			},

			/**  编辑器  */
			qeBeforeUpload() {
				// 显示loading动画
				this.quillUpdateImg = true
			},

			qeUploadSuccess(res,file){
				console.log(res);
				let quill = this.$refs.myQuillEditor.quill
				// 如果上传成功
				if (res.code == 200 ) {
					// 获取光标所在位置
					let length = quill.getSelection().index;
					// 插入图片  res.url为服务器返回的图片地址
					quill.insertEmbed(length, 'image', res.url)
					// 调整光标到最后
					quill.setSelection(length + 1)
				} else {
					this.$message.error('图片插入失败')
				}
				// loading动画消失
				this.quillUpdateImg = false
			},
			qeUploadError(){
				this.quillUpdateImg = false
			},
			onEditorChange({editor, html, text}) {
				this.goodsModel.information = html
			},
			setCategories(){
				getAllCategory().then((res)=>{
					let data = res.data.data;
					this.categoryOptions = data;
				})
			},
			/**  编辑器  */
			handleAdd(){
				this.setCategories();
				this.goodsModel = {
					bazarPrice: '',
					category: "",
					categoryId: '',
					comment: 0,
					createTimeStr: "",
					description: "",
					id: 0,
					images: [],
					information: '',
					liked: '',
					price: '',
					sale: 0,
					status: 1,
					stock: 0,
					thumb:'',
					title: "",
					view: 0
				}
				this.pictures = []
				this.formVisible = true
			},
			handleState(index,row){
				let question = '确定要下架该商品吗？'
				let params = {
					id: row.id,
					status: 0
				}
				if(row.status==0){
					question = '确定要上架该商品吗？'
					params.status = 1;
				}
				this.$confirm(question, '提示', {}).then(() => {
					this.editLoading = true;
					goodsStatus(params).then((res) => {
						if(res.code == 200){
							this.editLoading = false;
							//NProgress.done();
							this.$message({
								message: params.status==0?'已下架':'已上架',
								type: 'success'
							});
							this.getGoods();
						}
					});
				})
			},
			handleEdit(index,row){
				this.setCategories();
				this.goodsModel = row;
				this.formVisible = true;
				this.pictures = [];
				for(let i=0;i<row.images.length;i++){
					this.pictures.push({
						url:this.renderImage(row.images[i].url)
					})
				}
			},
			handleDel(row){
				this.$message({
					type: 'error',
					message:'暫時不支持刪除'
				})
			},
			handleCurrentChange(val){
				this.pager.page = val;
				this.getGoods();
			},
			handleSizeChange(val){
				this.pager.limit = val
				this.getGoods();
			},
			search(type){
				if(type == 0){
					this.filters.title = '';
					this.filters.categoryId = '';
				}
				this.getGoods()
				this.pager.page = 1;
			},
			batchRemove(){

			},
			onUploadSuccess(res,file){
				let url = res.data.path;
				this.goodsModel.thumb = url;
			},
			onUploadListSuccess(res,file){
				let url = res.data.path;
				this.goodsModel.images.push({url:url})
				this.pictures.push({url:this.renderImage(url)})
			},
			getGoods(){
				this.listLoading = true
				let _this = this;
				let param = {
					page: _this.pager.page,
					rowSize:_this.pager.limit,
					title: _this.filters.title,
					categoryId:_this.filters.categoryId
				}
				getGoodsData(param).then(resp=>{
					let result = resp.data;
					if(result.code == 200){
						let data = result.data;
						_this.pager.total = data.totalRow;
						_this.goodsData = data.list;
						_this.listLoading = false;
					}else{
						_this.$message({
							type:'error',
							message:'请求失败'
						})
					}
				})
			},
			submit(){
				let _this = this;
				saveGoodsData(this.goodsModel).then(res=>{
					console.log(res);
					if(res.code == 200){
						_this.$message({
							type:'success',
							message:'保存成功'
						})
						_this.formVisible = false;
						_this.getGoods();
					}else{
						_this.$message({
							type:'error',
							message:res.msg
						})
					}
				})
			},
			removeListImage(file,fileList){
				this.goodsModel.images = [];
				this.pictures = []
				for(let i=0;i<fileList.length;i++){
					this.pictures.push({url:fileList[i].url})
				 	let url = fileList[i].url.replace(this.imageService,'');
					this.goodsModel.images.push({url:url})
				}
			}
		},
		mounted() {
			this.getGoods();
			// this.setCategories();
		}
	}
</script>
